<template>
	<div style="width: 100%; overflow: auto">
		<div :id="FieldItem?.tag + FieldItem?.formId" :style="{ height: FieldItem?.attrs.height + 'px' }"></div>
	</div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
import { BarChart, LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { TablePageType, TabFieldType } from '/@/components/Linxyun/custom/DataStructs/commontype';

echarts.use([TitleComponent, TooltipComponent, GridComponent, LegendComponent, BarChart, LineChart, CanvasRenderer]);

const props = withDefaults(
	defineProps<{
		pageInfo?: TablePageType;
		pageData?: any;
		inputData: Record<string, any>;
		globalData?: any;
		FieldItem: TabFieldType | null;
	}>(),
	{
		pageData: {},
		globalData: null,
		FieldItem: null,
	}
);
const { FieldItem, pageData } = toRefs(props);
const { proxy } = <any>getCurrentInstance();

onMounted(() => {
	init();
});

// 数据发生变化重新渲染
watch(
	() => props.pageData[FieldItem.value?.options.tableData],
	() => {
		init();
	}
);
const init = () => {
	// 处理成多组形式需要的数据格式
	let XData = ref<any[]>([]); // x轴坐标数据
	let seriesTmp = ref<any[]>([]); // 处理好的完整数据
	let YKey = ref(FieldItem.value?.options.classDefine.BindVar); // 要显示的数据字段
	let YValue = ref<any[]>([]); // 显示字段的数据
	let valuetmp = ref<any[]>([]); // 固定显示字段时用的变量，保存要显示的字段名称

	/**
	 * @tableData 组件绑定的数组数据
	 * @XBindVar x轴的绑定字段
	 * @BindVar 要取的数值变量
	 * @classDefine => @BindVar 分类绑定变量，要显示的字段
	 * @classDefine => @options 固定的显示字段列表 label显示名  value对应显示字段的值
	 * @classDefine => @isFixed 是否固定了显示字段
	 */

	const tableData = ref(props.pageData[FieldItem.value?.options.tableData]);
	console.log('tableDatatableDatatableData', tableData.value);
	if (tableData.value && tableData.value.length && tableData.value[0][FieldItem.value?.options.XBindVar]) {
		tableData.value.forEach((item: Record<string, any>, i: number) => {
			// 获取x轴数据
			if (item[FieldItem.value?.options.XBindVar]) {
				XData.value.push(item[FieldItem.value?.options.XBindVar]);
			}
			// 获取分类
			if (!FieldItem.value?.options.classDefine.isFixed) {
				seriesTmp.value.push(item[YKey.value]);
			} else {
				FieldItem.value?.options.classDefine.options.forEach((ops: Record<string, any>) => {
					if (ops.value === item[YKey.value]) {
						seriesTmp.value.push(ops.label);
						valuetmp.value.push(item[YKey.value]);
					} else {
						seriesTmp.value.push(ops.label);
						valuetmp.value.push(ops.value);
					}
				});
			}

			// 此时x轴数据和显示字段已全部获取
			if (i === tableData.value.length - 1) {
				XData.value = Array.from(new Set(XData.value));
				// 如果开启了补值，根据配置进行补值处理
				if (FieldItem.value?.options.supplyValue.ifSpyVal) {
					if (FieldItem.value?.options.supplyValue.timeType === 'year') {
						if (FieldItem.value?.options.supplyValue.spyTimeFunc === 'near') {
							XData.value = supplyValueNear(XData.value);
						} else {
							XData.value = supplyValueCurrent(XData.value);
						}
					} else if (FieldItem.value?.options.supplyValue.timeType === 'month') {
						if (FieldItem.value?.options.supplyValue.spyTimeFunc === 'current') {
							XData.value = supplyValueOneToNow(XData.value);
						} else {
							XData.value = supplyValueLatelyM(XData.value);
						}
					}
				}
				seriesTmp.value = Array.from(new Set(seriesTmp.value));
				valuetmp.value = Array.from(new Set(valuetmp.value));
				const forArr = FieldItem.value?.options.classDefine.isFixed ? valuetmp : seriesTmp;
				// 获取显示字段所对应的值
				const lastValArr = ref<number[]>([]);
				for (let x = 0; x < XData.value.length; x++) {
					for (let i = 0; i < forArr.value.length; i++) {
						for (let j = 0; j < tableData.value.length; j++) {
							!YValue.value[i] && YValue.value.push([]);
							if (tableData.value[j][FieldItem.value?.options.XBindVar] === XData.value[x] && tableData.value[j][YKey.value] === forArr.value[i]) {
								YValue.value[i] && YValue.value[i].splice(x, 1, tableData.value[j][FieldItem.value?.options.BindVar]);
								break;
							} else if (tableData.value[j][YKey.value] === forArr.value[i]) {
								let fdFixed;
								if (FieldItem.value?.options.supplyValue.fixedLabelVal.length) {
									fdFixed = FieldItem.value?.options.supplyValue.fixedLabelVal.filter(
										(ft: Record<string, any>) => ft.label === tableData.value[j][YKey.value]
									);
								}
								if (fdFixed && fdFixed.length) {
									if (fdFixed[0].value !== 'lastVal') {
										YValue.value[i].length <= x && YValue.value[i].push(fdFixed[0].value);
									} else {
										YValue.value[i].length <= x && YValue.value[i].push(0);
										lastValArr.value[i] !== i && lastValArr.value.push(i);
									}
								} else {
									YValue.value[i].length <= x && YValue.value[i].push(0);
								}
							} else {
								YValue.value[i].length <= x && YValue.value[i].push(0);
							}
						}
					}
				}
				// 设置了补值的标签，且补值内容为最后一次的值时，处理它的值
				lastValArr.value.forEach((lsi) => {
					let number, index;
					for (let i = YValue.value[lsi].length - 1; i >= 0; i--) {
						if (YValue.value[lsi][i] > 0) {
							index = i;
							number = YValue.value[lsi][i];
							break;
						}
					}
					for (let i = index as number; i < YValue.value[lsi].length; i++) {
						YValue.value[lsi][i] = number;
					}
				});

				YValue.value = YValue.value.filter((s: any[]) => s.length);
				// 整理数据格式
				seriesTmp.value.forEach((item, i) => {
					seriesTmp.value.splice(i, 1, { [YKey.value]: item, name: YKey.value, [FieldItem.value?.options.BindVar]: YValue.value[i] });
				});
			}
		});
	}
	console.log('seriesTmpseriesTmp', [...seriesTmp.value], [...XData.value]);

	// 处理为echart需要的数据格式
	if (props.pageData[FieldItem.value?.options.tableData]) {
		FieldItem.value!.options.series = [];
		FieldItem.value!.options.xAxis.data = XData.value;
		seriesTmp.value.forEach((item: Record<string, any>, index: number) => {
			if (item.name === FieldItem.value?.options.classDefine.BindVar) {
				FieldItem.value?.options.series.push({ data: [] });
				FieldItem.value!.options.series[index].name = item[FieldItem.value?.options.classDefine.BindVar];
				FieldItem.value!.options.series[index].data = item[FieldItem.value?.options.BindVar];
				FieldItem.value!.options.series[index].type = FieldItem.value?.execTag === 'sBar' ? 'bar' : 'line';
			}
		});
	}
	console.log('[echarts] [bar And Line] [options]：', FieldItem.value?.options);
	setTimeout(() => {
		const chartDom = document.getElementById(FieldItem.value?.tag + FieldItem.value?.formId)!;
		const myChart = echarts.init(chartDom);
		myChart.setOption(FieldItem.value?.options);
		proxy.$forceUpdate();
		window.addEventListener('resize', () => {
			if (chartDom.offsetWidth > 400 || chartDom.offsetHeight > 300) {
				myChart.resize();
			}
		});
	}, 500);
};

// 折线图和柱状图补值 数据起始年
const supplyValueCurrent = (XData: any[]) => {
	const XDatatmp = [];
	const date = new Date();
	let nowYear = date.getFullYear();
	let year = XData[0].substring(0, 4);
	const number = Number((nowYear - year) / FieldItem.value?.options.supplyValue.step) + 1;
	let YUnit;
	if (/['年','/','-']/.test(XData[0][4])) YUnit = XData[0][4];
	for (let spyNmb = 0; spyNmb < number; spyNmb++) {
		if (nowYear > year) {
			XDatatmp.unshift(nowYear + (YUnit || ''));
			nowYear -= FieldItem.value?.options.supplyValue.step;
		} else {
			XDatatmp.unshift(year + (YUnit || ''));
		}
	}
	return XDatatmp;
};

// 折线图和柱状图补值 近一年
const supplyValueNear = (XData: any[]) => {
	const XDatatmp = [];
	const date = new Date();
	let year = date.getFullYear();
	let month = Number(String(date.getMonth() + 1).padStart(2, '0'));
	let YUnit;
	let MUnit;
	if (/['年','/','-']/.test(XData[0][4])) YUnit = XData[0][4];
	if (XData[0][XData[0].length - 1] === '月') MUnit = '月';
	let number;
	FieldItem.value?.options.supplyValue.step > 1 ? (number = Number(12 / FieldItem.value?.options.supplyValue.step) + 1) : (number = 12);
	for (let spyNmb = 0; spyNmb < number; spyNmb++) {
		if (spyNmb > 0) month -= FieldItem.value?.options.supplyValue.step;
		if (month > 0) {
			XDatatmp.unshift(year + (YUnit || '') + String(month).padStart(2, '0') + (MUnit || ''));
		} else {
			year--;
			month = 13 - FieldItem.value?.options.supplyValue.step;
			XDatatmp.unshift(year + (YUnit || '') + String(month).padStart(2, '0') + (MUnit || ''));
		}
	}
	return XDatatmp;
};

// 折线图和柱状图补值 1号至当前
const supplyValueOneToNow = (XData: any[]) => {
	console.log('XDataXDataXData', XData);
	const XDatatmp = [];
	const days = parseInt(String(new Date().getDate()).padStart(2, '0')) / FieldItem.value?.options.supplyValue.step;
	let MUnit;
	if (XData[0][XData[0].length - 1] === '月') MUnit = '月';
	let prefix;
	if (XData[0].length > 2) prefix = XData[XData.length - 1].substring(0, XData[0].length - 2);
	for (let i = 1; i <= days; i++) {
		XDatatmp.push(prefix + String(i * FieldItem.value?.options.supplyValue.step).padStart(2, '0') + (MUnit || ''));
	}
	return XDatatmp;
};
// 折线图和柱状图补值 近一月
const supplyValueLatelyM = (XData: any[]) => {
	const XDatatmp = [];
	let MUnit = ref('');
	if (XData[0][2] === '月') MUnit.value = '月';
	let DUnit = ref('');
	if (/['日','号']/.test(XData[0][XData.length - 1])) DUnit = XData[0][XData.length - 1];
	const days = Number(30 / FieldItem.value?.options.supplyValue.step);
	for (var j = 0; j <= days; j++) {
		let thirtyDays = new Date(new Date().toLocaleDateString()).getTime() - j * 3600 * (24 * FieldItem.value?.options.supplyValue.step) * 1000;
		XDatatmp.unshift(getTime(thirtyDays, MUnit.value, DUnit.value));
	}
	return XDatatmp;
};

const getTime = (nS: number, MUnit: string, DUnit: string) => {
	const date = new Date(nS);
	// 获取当前的年份
	let y = String(date.getFullYear()).padStart(2, '0');
	let m = String(date.getMonth() + 1).padStart(2, '0');
	let d = String(date.getDate()).padStart(2, '0');
	return y + m + (MUnit || '') + d + (DUnit || '');
};

defineExpose({ init });
</script>

<style lang="scss" scoped></style>
